package cn.com.zsw.gblog.config;


import com.mongodb.client.gridfs.model.GridFSFile;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * @Author shiwangZhou
 * @Description
 * @Date 2020-09-04 19:24
 */
@Component
public class MongoGridFsDao {
    @Autowired
    GridFsTemplate gridFsTemplate;


    public String uploadFile(MultipartFile multipartFile) throws Exception {

        InputStream inputStream = multipartFile.getInputStream();
        String filename = multipartFile.getOriginalFilename();
        String contentType = multipartFile.getContentType();
        ObjectId objectId;
        try {
            objectId = gridFsTemplate.store(inputStream, filename, contentType);
        } catch (Exception e) {
            throw new RuntimeException("文件上传mongo失败", e);
        }

        return objectId.toString();
    }

    /**
     * 根据文件Id查询文件
     *
     * @param fileId 文件ID
     * @return 文件流
     */
    public InputStream downloadByObjectId(String fileId) throws Exception {

        if (null == fileId || fileId.trim().length() < 1) {
            throw new IllegalArgumentException("[findOneByObjectId]查询objectId不能为空");
        }
        Query query = Query.query(Criteria.where("_id").is(fileId));
        GridFSFile gridFsFile = gridFsTemplate.findOne(query);
        if (gridFsFile != null) {
            GridFsResource resource = gridFsTemplate.getResource(gridFsFile);
            return resource.getInputStream();
        }
        return null;

    }
}
